package com.qdlc.p2p.common.constant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;

import com.qdlc.p2p.common.core.redis.JedisCache;
import com.qdlc.p2p.common.core.redis.JedisCacheFactory;
import com.qdlc.p2p.common.util.StringUtil;

/**
 * 全局变量或常量
 *
 * @author wuaj
 */
public class Global {

    /** 表前缀 */
    public static final String DB_PREFIX = "ms_";

    // other common data
    /** 保存数据 */
    public static final ThreadLocal transferThreadLocal = new ThreadLocal();

    /** 保存IP用 */
    private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<String>();

    /** 任务执行结果 */
    public static Map TASK_RESULT_MAP = new ConcurrentHashMap();

    public static Map<String, Object> getTransfer() {
        Map<String, Object> map = (Map<String, Object>) transferThreadLocal.get();
        return map == null ? new HashMap<String, Object>() : map;
    }

    public static void setTransfer(String key, Object value) {
        Map<String, Object> map = getTransfer();
        map.put(key, value);
        transferThreadLocal.set(map);
    }

    public static String getIP() {
        Object retObj = Global.ipThreadLocal.get();
        return retObj == null ? "" : retObj.toString();
    }

    public static void setIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        /*if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
		}*/
        ip = StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) ? request.getHeader("X-Real-IP") : "";
        ip = StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip) ? request.getRemoteAddr() : "";
        if (!StringUtil.isEmpty(ip)) {
            String[] ipArray = ip.split(",");
            if (ipArray != null && ipArray.length > 1) {
                Global.ipThreadLocal.set(ipArray[0]);
                return;
            }
            Global.ipThreadLocal.set(ip);
            return;
        }
        Global.ipThreadLocal.set("");
    }

    public static void setIP(String ip) {
        Global.ipThreadLocal.set(ip);
    }

    public static Map BORROW_CONFIG_MAP;

    public static List BORROW_CONFIG_LIST;

    public static Object getBorrowConfig(long borrowType) {
        return BORROW_CONFIG_MAP == null ? null : BORROW_CONFIG_MAP.get(borrowType);
    }

    public static void putCallBackUrl(String url) {
        JedisCache<String> jedisCache = JedisCacheFactory.newInstance(String.class);
        jedisCache.set(url, StringUtil.getRandomString(11));
    }

    public static String getCallBackToken(String url) {
        JedisCache<String> jedisCache = JedisCacheFactory.newInstance(String.class);
        String token = jedisCache.get(url);
        return token == null ? "" : token;
    }
}
